package cn.wolfcode.ssm.controller;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.query.QueryObject;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("employees")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping
    public ModelAndView list(@ModelAttribute("qo") QueryObject qo){
        Map<String,Object> map = new HashMap<>();
        map.put("result",employeeService.query(qo));
        return new ModelAndView("/employee/list",map);
    }
    @DeleteMapping("/{employeeId}")
    public JSONResult delete(@PathVariable("employeeId") Long employeeId){
        JSONResult result = new JSONResult();
        try {
            if(employeeId != null){
                employeeService.delete(employeeId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
    @PostMapping
    public JSONResult save(Employee employee){
        JSONResult result = new JSONResult();
        try {
                employeeService.save(employee);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
    @PutMapping
    public JSONResult update(Employee employee){
        JSONResult result = new JSONResult();
        try {
                employeeService.update(employee);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
